﻿using BCDto.Common.IP;
using BCService.Common.IP;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace BCComponent.Task.UpdateIPAddressRecord
{
    public class UpdateIPAddressRecord:IUpdateIPAddressRecord
    {
        private readonly IIPAddressRecordService ipAddressRecordService;


        public UpdateIPAddressRecord(IIPAddressRecordService ipAddressRecordService)
        {
            this.ipAddressRecordService = ipAddressRecordService;
        }

        public void Process() {
            string directory = Directory.GetCurrentDirectory();
            string fileName = "ip.txt";
            string path = Path.Combine(directory, fileName);
            if (!File.Exists(path)) {
                return;
            }
            string[] txtStr;
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            using (FileStream fs = new FileStream(path, FileMode.Open))
            {
                StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("gb2312"), true);
                txtStr = sr.ReadToEnd().Split("\r\n");
            }

            List<IPAddressRecordDto> list = new List<IPAddressRecordDto>();
            for (int i = 1; i < txtStr.Length; i++) {
                string txt = txtStr[i];
                while (txt.Contains("  "))
                {
                    txt = txt.Replace("  ", " ");
                }
                if (string.IsNullOrWhiteSpace(txt)) {
                    continue;
                }
                if (txt.Contains("255.255.255.0")) {
                    break;
                }
                string[] ipStr = txt.Split(" ");
                    
                IPAddressRecordDto addressRecordDto = new IPAddressRecordDto();
                addressRecordDto.StartIP = ipStr[0];
                addressRecordDto.EndIP = ipStr[1];
                addressRecordDto.IANA = ipStr[2];
                addressRecordDto.ReservedAddress = ipStr.Length == 3 ? "" : ipStr[3];
                list.Add(addressRecordDto);
            }
            if (list.Count > 0)
            {
                ipAddressRecordService.Import(list);
            }
            File.Delete(path);
        }
    }
}
